package com.cysion.study.widget;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import com.cysion.study.ktbox.base.BaseActivity;
import com.cysion.study.R;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 图片Activity基类
 *
 * @author moshouguan
 */
public class BasePicActivity extends BaseActivity implements  PicChooserDialog.OnPicChooserListener {


    private final static int CROP = 200;
    private final static String FILE_SAVEPATH = Environment.getExternalStorageDirectory().getAbsolutePath()
            + "/pet/pic/";
    private Uri origUri;
    private Uri cropUri;
    private File protraitFile;
    private Bitmap protraitBitmap;
    private String protraitPath;

    static final String[] PERMISSIONS = new String[]{Manifest.permission.CAMERA};
    private static final int REQUEST_CODE_SETTING = 300;
    private static final int REQUEST_CODE_PERMISSION = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initPhotoError();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }

    }


    private void initPhotoError() {
        // android 7.0系统解决拍照的问题
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }



    public void takePhoto() {
        PicChooserDialog dialog = new PicChooserDialog(this, R.style.bottom_dialog);
        dialog.setListner(this);
        dialog.show();
    }

    @Override
    public void onClickFromGallery(View view) {
        startImagePick();
    }

    @Override
    public void onClickFromCamera(View view) {
        startActionCamera();
    }

    /**
     * 选择图片裁剪
     *
     */
    private void startImagePick() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(Intent.createChooser(intent, "选择图片"), ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
    }

    private String imageName;
    /**
     * 相机拍照
     *
     */
    private void startActionCamera() {
//        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, this.getCameraTempFile());
//        startActivityForResult(intent, ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);

        String SAVE_PIC_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Buyers/saveImage/";

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File dir = new File(SAVE_PIC_PATH);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        imageName = SAVE_PIC_PATH + getNowTime() + ".png";

        File file = new File(imageName);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {

            }
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(intent, ImageUtils.PHOTO_REQUEST_TAKEPHOTO);
    }

    //获取当前时间
    @SuppressLint("SimpleDateFormat")
    private String getNowTime() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("MMddHHmmssSS");
        return dateFormat.format(date);
    }

    /**
     * 拍照后裁剪
     *
     * @param data
     *            原始图片
     *            裁剪后图片
     */
    private void startActionCrop(Uri data) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(data, "image/*");
        intent.putExtra("output", this.getUploadTempFile(data));
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);// 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", CROP);// 输出图片大小
        intent.putExtra("outputY", CROP);
        intent.putExtra("scale", true);// 去黑边
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        startActivityForResult(intent, ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
    }

    // 裁剪头像的绝对路径
    private Uri getUploadTempFile(Uri uri) {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            File savedir = new File(FILE_SAVEPATH);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        } else {
//            UIHelper.showToast(getString(R.string.submit_head_pic_error));
            return null;
        }
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(uri);

        // 如果是标准Uri
        if (!TextUtils.isEmpty(thePath)) {
            thePath = ImageUtils.getAbsoluteImagePath(this, uri);
        }
        String ext = FileUtils.getFileFormat(thePath);
        ext = TextUtils.isEmpty(ext) ? "jpg" : ext;
        // 照片命名
        String cropFileName = "osc_crop_" + timeStamp + "." + ext;
        // 裁剪头像的绝对路径
        protraitPath = FILE_SAVEPATH + cropFileName;
        protraitFile = new File(protraitPath);

        cropUri = Uri.fromFile(protraitFile);
        return this.cropUri;
    }

    // 拍照保存的绝对路径
    private Uri getCameraTempFile() {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            File savedir = new File(FILE_SAVEPATH);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        } else {
//            UIHelper.showToast(getString(R.string.submit_head_pic_error));

            return null;
        }
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        // 照片命名
        String cropFileName = "osc_camera_" + timeStamp + ".jpg";
        // 裁剪头像的绝对路径
        protraitPath = FILE_SAVEPATH + cropFileName;
        protraitFile = new File(protraitPath);
        cropUri = Uri.fromFile(protraitFile);
        this.origUri = this.cropUri;
        return this.cropUri;
    }

    private Uri setBitmapTempFile(Bitmap bitmap) {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            File savedir = new File(FILE_SAVEPATH);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        } else {
//            UIHelper.showToast( getString(R.string.submit_head_pic_error));
            return null;
        }
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(new Date());
        // 照片命名
        String cropFileName = "osc_camera_" + timeStamp + ".jpg";
        // 裁剪头像的绝对路径
        protraitPath = FILE_SAVEPATH + cropFileName;
        protraitFile = new File(protraitPath);
        try {
            ImageUtils.saveImage(this, protraitPath, bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        cropUri = Uri.fromFile(protraitFile);
        this.origUri = this.cropUri;
        return this.cropUri;
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        System.out.println("onActivityResult");


        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA:
                    startActionCrop(origUri);// 拍照后裁剪
                    break;
                case ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP:
                    startActionCrop(data.getData());// 选图后裁剪
                    break;
                case ImageUtils.PHOTO_REQUEST_TAKEPHOTO://拍照
//                    startPhotoZoom(Uri.fromFile(new File(AppContext.getInstance().SAVE_PIC_PATH, imageName)), 880);
//                    File file1 = new File(imageName);
//                    updateAvatarInServer(file1);
                    if (imageName != null) {

                        int degree = PhotoUtils.readPictureDegree(imageName);
                        Bitmap bitmap = FileCompressUtil.com(imageName);
                        if (bitmap != null) {
                            Bitmap newbitmap = PhotoUtils.rotaingImageView(degree,
                                    bitmap);
                            String mCompressPhotopath = PhotoUtils.saveBitmap2file(
                                    newbitmap, System.currentTimeMillis() + ".jpg");
                            if (TextUtils.isEmpty(mCompressPhotopath)) {
                                return;
                            }
                            File file = new File(mCompressPhotopath);
//                            updateAvatarInServer(file);
                            outputBitmap(protraitBitmap, mCompressPhotopath);
                        }

                    }
                    break;
                case ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD:
                    Uri uri = data.getData();
                    if (uri != null) {
                        protraitPath = ImageUtils.getAbsoluteImagePath(this, uri);
                        protraitFile = new File(protraitPath);
//                        outputBitmap(null,ImageUtils.getAbsoluteImagePath(this, uri));
                    }
                    if (uri == null) {
                        //use bundle to get data
                        Bundle bundle = data.getExtras();
                        if (bundle != null) {
                            Bitmap photo = (Bitmap) bundle.get("data"); //get bitmap
                            //spath :生成图片取个名字和路径包含类型
                            setBitmapTempFile(photo);

                        } else {
//                            UIHelper.showToast("获取图片错误");
                            return;
                        }
                    }
                    // 获取头像缩略图
                    if (!TextUtils.isEmpty(protraitPath) && protraitFile.exists()) {
//                        protraitBitmap = ImageUtils.loadImgThumbnail(protraitPath, 200, 200);
                        protraitBitmap = ImageUtils.getBitmapByPath(protraitPath);
                        protraitPath=  compressImage(protraitPath);
                        outputBitmap(protraitBitmap, protraitPath);
                    }
                    break;
            }
        }
    }



    public String compressImage(String picFileName) {
        Bitmap bitmap = BitmapUtil.decodeFile(picFileName, 960);
//        File file = saveBitmap(bitmap, this);
//
//        return file.getAbsolutePath();
//        Bitmap image = FDBitmapUtil.decodeFile(picFileName, 1000);
//        FDFileUtil.deleteFile(new File(picFileName), this);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        float options = 90;
        while (baos.toByteArray().length / 1024 > 200 && options > 80) { // 循环判断如果压缩后图片
            baos.reset();// 重置baos即清空baos
            bitmap.compress(Bitmap.CompressFormat.JPEG, (int) options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 5f;// 每次都减少10
        }
        File file = FileUtils.createFileWithSuffix(".jpg", this);
        System.out.println("压缩后大小 " + (baos.toByteArray().length / 1024)+"==options="+options);
        // 保存新文件
        try {
            FileOutputStream out = new FileOutputStream(file);
            out.write(baos.toByteArray());
            out.flush();
            out.close();
            return file.getAbsolutePath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "";
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
    public void outputBitmap(Bitmap bitmap, String path) {

    }

    @Override
    public int getLayoutId() {
        return 0;
    }

    @Override
    public void initView() {

    }

    @Override
    public void closeMvp() {

    }
}
